//  配置
var _config = {
  //  base: 'http://t.imaisu.com',
  base: '',
  getProduct: '/api/product', //  查询货品
  getBaseUrl: '/api/base_url', //  查询根域名
  getDeliverySource: '/api/delivery_source', //  查询投放来源
  getTemplate: '/api/template',
  getLongUrl: '/api/long_url'
}

//  业务逻辑
var _main = {
  modalForm : {

  },
  data: {
  },
  //  点创建按钮
  submitCreateForm: function() {
    let _phone = document.querySelector('#phone').value;
        _phone = _phone.split('\n');
    _utils.post(_config.creatShortLink, {
      phones: _phone ? this.data.phoneArr.concat(_phone) : this.data.phoneArr,
      delivery_time: document.querySelector('#delivery_time').value,
      template_id: document.querySelector('#template_id').value,
      base_url_id: document.querySelector('#base_url').value,
      product_id: document.querySelector('#product').value,
      delivery_source_id: document.querySelector('#delivery_source').value
    }, (res) => {
      console.log(res)
      document.querySelector('#create_result').value = this.servlize(res)
    })
  },
  getSelected: function (obj) {
    var _r = obj.options[obj.selectedIndex]
    return {
      text: _r.text,
      value: _r.value
    }
  },
  bindEvents: function () {
    var _objs = {
      modal: document.getElementById('template_modal'),
      id: document.getElementById('tpl_id'),
      name: document.getElementById('tpl_name'),
      text: document.getElementById('tpl_text'),
      add: document.getElementById('tpl_add'),
      cancel: document.getElementById('tpl_cancel'),
    }
    this.modalForm = _objs;
    var t = this;
    var _optionsArr = ['long_url', 'base_url', 'product', 'delivery_source'];
    for (var i = 0; i < _optionsArr.length; i++ ){
      var _key = _optionsArr[i];
      var _strkey = _utils.toCamelCase(_key);
      var _parent = _utils.closest(document.getElementById(_key), { 'className': _strkey })
      //  给父级元素绑事件
      _parent.addEventListener('click', function(e){
        var _target = e.target;
        var _self = this;
        var _childs = _self.childNodes
        //  找输入框和下拉框子
        var _val, _select;
        for (var i = 0; i < _childs.length; i++ ) {
          if (_childs[i].className == 'Val') {
            _val = _childs[i];
          } else if (_childs[i].nodeName == 'SELECT') {
            _select = _childs[i];
          }
        }
        var _params = {};
        if (_target.className == "Add") {
          if (!_val.value) {
            alert('新增内容不可为空');
            return
          } else if (!confirm("确认新增: "+ _val.value)) {
            return
          }
          _params[_select.id] = _val.value;
          //  增加
          _utils.post(_config['get' + _self.className.replace(/^\w/, function(){
            return arguments[0].toUpperCase()
          })], _params, (res) => {
            if (res.msg == 'exist') {
              alert(res.notice);
            } else {
              alert('新增成功！');
              _val.value = '';  //  添加完成后删除框子里的内容
            }
            console.log(res)
            t.getInitData();
          })
        } else if (_target.className == "Del") {
          if(!confirm("确认删除: " + t.getSelected(_select).text)) return
          _params[_select.id] = t.getSelected(_select).text;
          //  删除
          _utils.del(_config['get' + _self.className.replace(/^\w/, function(){
            return arguments[0].toUpperCase()
          })], _params, (res) => {
            if (res.msg == 'ok') {
              alert('删除成功！');
            }
            console.log(res)
            t.getInitData();
          })
        }
      })
    }

    document.getElementById('template_add').addEventListener('click', function(){
      if (!document.querySelector('#template_name').value || !document.querySelector('#template_text').value) {
        alert("新增短信模板名称和文案不能为空")
        return
      }
      _utils.post(_config.getTemplate, {
        name: document.querySelector('#template_name').value,
        text: document.querySelector('#template_text').value
      }, (res) => {
        console.log(res)
        t.getInitData();
      })
    })

    document.getElementById('template_text').addEventListener('input', function() {
      var template_words = document.querySelector('#template_text').value.replace(/({s})|({{url}})/ig, 'xxxxxxxxxxxxxxxxxx');
      var words_unmber = template_words.length;
      console.log(words_unmber);
      var _n = document.getElementById("tmpTxtLenErr");
      //document.querySelector('#words_number').innerText = words_unmber + "/70";
      if( words_unmber > 70) {
        _n.style.display = "block"
      } else {
        _n.style.display = "none" }
    })

  },
  setSelectOptions: function (arr, key) {
    var _res = '';
    arr = _utils.sortSelect(arr);
    arr.forEach((e, i) => {
      _res += '<option value="' + e['id'] + '" >' + e[key] + '</option>'
    })
    return _res
  },
  setTableDate: function (data) {
    var _r = "<tr>\
      <th>id</th>\
      <th>短信模板</th>\
      <th>文案配置</th>\
      <th>操作</th>\
    </tr>";
    data.forEach((e,i) => {
      _r += '<tr>';
      /*for (var j in e ) {
        _r += '<td>' + e[j] + '</td>'
      }*/
      _r += '<td>' + e['id'] + '</td><td>' + e['name'] + '</td>'
      _r += '<td title="' + e['text'] + '"><textarea class="copyInp" id="' + e['id'] + '" readOnly >' + e['text'] + '</textarea>&emsp;<a href="javascript:void(0)" onclick="copyById(' + e['id'] + ')">[复制]</a></td>';
      _r += '<td >\
        <a onclick="delCol({ id: \'' + e['id']+ '\', name: \'' + e['name']+ '\', text: \'' + e['text'] + '\' })" href="###">删除</a>\
        &emsp;<a onclick="modiCol({ id: \'' + e['id']+ '\', name: \'' + e['name']+ '\', text: \'' + e['text'] + '\' })" href="###">修改</a>\
        </td>'
      _r += '</tr>';
    })
    return _r
  },
  modiColHanlder: function (data) {
    var t = _main;
    _utils.openMask();
    t.modalForm.modal.style.display = "block";
    t.modalForm.id.innerHTML = data.id;
    t.modalForm.name.value = data.name;
    t.modalForm.text.value = data.text;
    t.modalForm.add.onclick = function () {
      _utils.put(_config.getTemplate, {
        template_id: data.id,
        name: t.modalForm.name.value,
        text: t.modalForm.text.value
      }, (res) => {
        console.log(res)
        t.getTemplateData();
        _utils.closeMask();
        t.modalForm.modal.style.display = "none";
      })
    }
    t.modalForm.cancel.onclick = function () {
      t.modalForm.modal.style.display = "none";
      _utils.closeMask();
    }
  },
  delColHanlder: function (data) {
    var t = _main;
    _utils.del(_config.getTemplate, {
      template_id: data.id,
      //  name: data.name,
      //  text: data.text
    }, (res) => {
      console.log(res)
      t.getTemplateData();
    })
  },
  //  序列化
  servlize: function (data) {
    var res = '';
    for (var i = 0; i< data.length; i++) {
      for (var j in data[i] ) {
       res += j + ':  ' + data[i][j] + '\n';
      }
    }
    return res
  },
  //  获取初始化数据\
  getInitData: function () {
    _utils.get(_config.getProduct, {
    }, (res) => {
      console.log(res)
      document.querySelector('#product').innerHTML = this.setSelectOptions(res, 'product_name');
    })
    _utils.get(_config.getBaseUrl, {
    }, (res) => {
      console.log(res)
      document.querySelector('#base_url').innerHTML = this.setSelectOptions(res, 'short_url');
    })
    _utils.get(_config.getDeliverySource, {
    }, (res) => {
      console.log(res)
      document.querySelector('#delivery_source').innerHTML = this.setSelectOptions(res, 'delivery_source');
    })
    this.getTemplateData();
    _utils.get(_config.getLongUrl, {
    }, (res) => {
      console.log(res)
      document.querySelector('#long_url').innerHTML = this.setSelectOptions(res, 'long_url');
    })
  },
  getTemplateData: function () {
    _utils.get(_config.getTemplate, {
    }, (res) => {
      console.log(res)
      document.querySelector('#template_table').innerHTML = this.setTableDate(res);
    })
  },
  copyById(id) {
    var copyText = document.getElementById('' + id);
    copyText.select();
    document.execCommand("copy");
    alert("短信文案已复制");
  },
  init: function () {
    this.getInitData();
    this.bindEvents();
  }
}
//  run
_main.init();
window.delCol = _main.delColHanlder;
window.modiCol = _main.modiColHanlder;
window.copyById = _main.copyById;
